import 'dart:io';

import 'package:flutter_tts/flutter_tts.dart';
import 'package:path_provider/path_provider.dart';

late FlutterTts flutterTts;
String audioDir = '';

class GlobalData {
  static int start = 10;
  static bool play = true;
  static bool isInit = false;
  static String ttsEngine = '';
  static bool showText = false;
}


Future<void> ttsInit() async {
  if (GlobalData.isInit) {
    GlobalData.isInit = true;
    return;
  }
  // tts init
  flutterTts = FlutterTts();

  if (!Platform.isAndroid) {
    return;
  }
  print('tts init');
  GlobalData.ttsEngine = await flutterTts.getDefaultEngine;
  print(GlobalData.ttsEngine.toString());

  var langs = await flutterTts.getLanguages;
  for (var l in langs) {
    if (l.contains('zh')) {
      print(l);
    }
  }
  await flutterTts.setLanguage('zh-CN');
  await flutterTts.setVolume(1.0);
  await flutterTts.setPitch(1.0);
  await flutterTts.setSpeechRate(1.0);
  await flutterTts.setQueueMode(1);

  //print('tts init success');

  // path init
  var dir1 = await getDownloadsDirectory();
  //print('init download dir:'+dir1!.path);
  audioDir = dir1!.path;

  String fileName = '$audioDir/a.wav';
  //print(fileName);
  await flutterTts.synthesizeToFile('开始', fileName);
  await flutterTts.awaitSynthCompletion(true);
  File(fileName).delete();
}

Future<String> textToAudio(String text1) async {
  if (!Platform.isAndroid) {
    return '';
  }

  var dir1 = await getDownloadsDirectory();
  //print('download dir:' + dir1!.path);
  audioDir = dir1!.path;
  String fileName = '$audioDir/a${GlobalData.start++}.wav';
  await flutterTts.synthesizeToFile(text1, fileName);
  //print('convert to file');
  await flutterTts.awaitSynthCompletion(true);
  
  //print(fileName);
  return fileName;
}
